<template>
  <div
    style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 1001; display: flex; flex-direction: column; background: #000"
    v-if="isQp"
  >
    <iframe src="/wrjsxt/live.html" frameborder="0" style="width: 100vw; flex: 1"></iframe>
    <!-- 遮挡层 -->
    <!-- <div class="overlay1">
      <div class="overlay-title">鹭栖湖</div>
      <div class="overlay-content">
        <div>无人机</div>
        <FullscreenOutlined style="color: #fff; font-size: 24px; cursor: pointer" @click="fullscreen" />
      </div>
    </div> -->
    <div class="btnBox">
      <div class="btn" @click="fullscreen">退出全屏</div>
    </div>
  </div>
  <div class="dangerous" v-if="isdangerousPop">
    <div class="dangerous-left" style="left: -469px">
      <iframe src="/wrjsxt/live.html" frameborder="0" style="width: 469px; height: 100%"></iframe>
      <!-- 遮挡层 -->
      <!-- <div class="overlay">
        <div class="overlay-title">鹭栖湖</div>
        <div class="overlay-content">
          <div>无人机</div>
          <FullscreenOutlined style="color: #fff; font-size: 24px; cursor: pointer" @click="fullscreen" />
        </div>
      </div> -->
      <div class="btnBox">
        <div class="btn" @click="fullscreen">全屏</div>
      </div>
    </div>

    <div id="box1">
      <div>
        <div class="flex title flex-0">
          <img src="/img/myimg/dangerous.svg" alt="" />
          <p>发生警报事件</p>
          <div class="flex type">
            <p class="name">
              <img src="/img/myimg/icon1.svg" alt="" class="icon" />
              警报类型
            </p>
            <p class="value">
              {{ data.appear_type }}
              <!-- AI识别 -->
            </p>
          </div>
          <img src="/img/myimg/close.svg" class="close pointer" alt="" @click="close" />
        </div>

        <div class="flex row-between m-t-13 rela flex-1">
          <div class="left flex col col-top">
            <div class="flex w100 flex-0">
              <div class="w50">
                <p class="name">
                  <img src="/img/myimg/icon1.svg" alt="" class="icon" />
                  警报时间
                </p>  
                <p class="value">
                  <!-- {{ dangerousData.createtime }} -->
                  {{ data.createtime }}
                </p>
              </div>

              <div class="flex-0 w50">
                <p class="name">
                  <img src="/img/myimg/icon1.svg" alt="" class="icon" />
                  警报地点
                </p>
                <p class="value">
                  鹭栖湖公园
                  <!-- {{ data.event_address }} -->
                  <!-- {{ dangerousData.event_address }} -->
                </p>
              </div>
            </div>

            <div class="m-t-24 flex-0 w100">
              <p class="name">
                <img src="/img/myimg/icon1.svg" alt="" class="icon" />
                警报内容
              </p>
              <p class="value">
                {{ data.content }}
                <!-- {{ dangerousData.content }} -->
              </p>
            </div>
            <div class="m-t-24 flex-0 w100">
              <p class="name">
                <img src="/img/myimg/icon1.svg" alt="" class="icon" />
                监控截图
              </p>
              <p class="value">
                <!-- <el-image style="width: 260px; height: 188px" :src="data.material_files" :zoom-rate="1.2" :max-scale="7"
                  :min-scale="0.2" :preview-src-list="[data.material_files]" show-progress fit="cover" /> -->
                <!-- <img :src="data.material_files" alt="" width="260"> -->
                <a-image style="width: 260px; height: 188px" :src="data.material_files" />
                <!-- <a-image width="188" :src="dangerousData.material_files" /> -->
              </p>
            </div>
          </div>

          <div class="right flex col col-top">
            <div class="ai-swiper" ref="AIRefSwpier">
              <p class="name">
                <img src="/img/myimg/icon1.svg" alt="" class="icon" />
                智能处置
              </p>
              <div class="ai-content">
                <div class="flex col col-top" ref="messageContentRef">
                  <div
                    :class="item.role === 'user' ? 'use-message' : 'ai-message'"
                    :style="{
                      marginTop: index == 0 ? '0' : ''
                    }"
                    v-for="(item, index) in messageData"
                    :key="index"
                    v-html="mdCtx.render(item.content)"
                  ></div>
                </div>
              </div>
              <!-- <div class="input-box flex">
                <input type="text" v-model="inputValue" @focus="focus" @blur="blur" />
                <button class="flex" @click="startRecorder">
                  <img src="/img/myimg/voice.png" alt="" />
                </button>
                <button @click="t_submit">发送</button>
              </div> -->
            </div>

            <!-- <div class="flex col-top col flex-0 event-btn">
              <p class="name">系统操作</p>
              <div class="btn-content flex">
                <button @click="showStaff = true">行动力量</button>
                 <button @click="simulation">模拟事态</button>
                <button @click="rescue">使用航空器</button>
                <button @click="handelOk">确认事件</button>
              </div>
            </div> -->
          </div>
        </div>
      </div>

      <Transition name="content">
        <div class="ai-content popup-ai" v-if="messageData.length">
          <div class="flex col col-top" ref="openRef">
            <div
              :class="item.role === 'user' ? 'use-message' : 'ai-message'"
              :style="{
                marginTop: index == 0 ? '0' : ''
              }"
              v-for="(item, index) in messageData"
              :key="index"
              v-html="mdCtx.render(item.content)"
            ></div>
          </div>
        </div>
      </Transition>

      <audio
        autoplay="autoplay"
        id="audio"
        src="https://pandiaochang.oss-cn-chengdu.aliyuncs.com/uploadfile/20220825/%E8%AD%A6%E6%8A%A5%E5%A3%B0-%E6%B8%B8%E6%88%8F%E6%8F%90%E7%A4%BA%E9%9F%B3_%E7%88%B1%E7%BB%99%E7%BD%91_aigei_com.mp3"
      ></audio>

      <!-- <div class="voice-swiper" v-if="show" ref="voiceSwiper">
        <span class="close" @click="stopRecorder"></span>
        <div class="img-box">
          <img src="/img/myimg/voice.png" alt="" />
        </div>
      </div> -->
    </div>
  </div>
</template>

<script setup>
import { useWidgetStore } from "@mars/common/store/widget"
import { store } from "@mars/common/store/global"
import axios from "axios"
import { onMounted, ref, defineProps, onUnmounted, computed, watch, inject, reactive } from "vue"
import Cookies from "js-cookie"
import { $message } from "@mars/components/mars-ui"
import { throttle } from "./throttle.ts"
import MarkdownIt from "markdown-it"
import AudioPlayer from "./audio.js"
import CryptoJS from "crypto-js"
import { RecordingData } from "./RecordingData.js"
import dayjs from "dayjs"
import $api from "@/utils/request.js"
import { FullscreenOutlined } from "@ant-design/icons-vue"

const day = dayjs(new Date()).format("YYYY-MM-DD HH:mm")
const itemUrl = ref("a5.mp4")
const getVideoUrl = (name) => {
  return new URL(`../../assets/video/${name}`, import.meta.url).href
}
const mdCtx = new MarkdownIt({
  breaks: true,
  typographer: true,
  html: true
})

const dangerousData = inject("dangerousData")
const isdangerousPop = inject("isdangerousPop")

watch(isdangerousPop, (newVal) => {
  if (!newVal) {
    messageData.value = []
  }
})

const widgetStore = useWidgetStore()
const props = defineProps(["id"])

const $realTime = computed(() => {
  return store.state.$realTime
})

const isQp = ref(false)

const fullscreen = () => {
  isQp.value = !isQp.value
}

const close = () => {
  isdangerousPop.value = false
  // widgetStore.dispatch("disable", "dangerous")
}

const showStaff = ref(false)

const messageContentRef = ref()

const inputValue = ref("")

const messageData = ref([])

const focusValue = ref(false)

const focus = () => {
  document.addEventListener("keypress", handlerKeyDown)
  focusValue.value = true
}

const blur = () => {
  document.removeEventListener("keypress", handlerKeyDown)
  focusValue.value = false
}

const handlerKeyDown = (e) => {
  if (e.charCode === 13 && inputValue.value) {
    t_submit()
  }
}

const tts_message_end = ref(false)

const submit = () => {
  if (!inputValue.value) {
    return
  }
  stop_tts()
  // if (!tts_message_end.value) {
  //   $message("正在暂停语音")
  //   return
  // }
  // tts_message_end.value = false

  messageData.value.push({
    role: "user",
    content: inputValue.value
  })
  getResult(inputValue.value)
  inputValue.value = ""
  setTimeout(() => {
    if (!messageContentRef.value) {
      return
    }
    messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
    openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
  })
}

const t_submit = throttle(() => {
  submit()
})

let bufferObj
let txt
const resultObj = reactive({
  conversationId: "",
  taskId: "",
  messageId: ""
})
const messageObj = reactive({
  conversationId: "",
  taskId: "",
  messageId: ""
})

const audioPlayer = new AudioPlayer({
  stopCallBack: () => {
    document.body.removeEventListener("keydown", addStart)
    startRecorder()
  }
})

const appKey = "app-PXYjOI1hQvgSctOtOUPU9sey"

const isResponesEnd = ref(true)

async function getResult(query) {
  if (!isResponesEnd.value) {
    return
  }
  isResponesEnd.value = false
  const resp = await fetch("https://smartai.chuangxing.ren/v1/chat-messages", {
    method: "post",
    headers: {
      "Content-Type": "application/json;audio/wav",
      Authorization: `Bearer ${appKey}`
    },
    body: JSON.stringify({
      conversation_id: resultObj.conversationId,
      user: "abc-123",
      inputs: {
        group_name: "智慧园区智能体",
        company_name: "西宁街道",
        yuanqu_name: "鹭栖湖公园"
      },
      query,
      response_mode: "streaming"
    })
  })
  // 获取流读取器
  const reader = resp?.body.getReader()
  // 字节数组转字符，创建文字解码器
  const decoder = new TextDecoder()

  document.body.addEventListener("keydown", addStart)

  const str = ref("")

  messageData.value.push({
    role: "admin",
    content: str
  })

  const unicodeToChar = async (text) => {
    str.value += text
    // str.value = await mdCtx.render(str.value)

    messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
    openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
    return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
      return String.fromCharCode(parseInt(p1, 16))
    })
  }

  // 循环读取数据
  while (true) {
    const { done, value } = await reader.read()
    if (done) {
      return
    }

    // 解码
    txt += decoder.decode(value, { stream: true })
    const lines = txt.split("\n")

    try {
      lines.forEach((message) => {
        if (message.startsWith("data: ")) {
          try {
            bufferObj = JSON.parse(message.substring(6))
          } catch (e) {
            // mute handle message cut off
            // console.log(e)
            return
          }
          if (bufferObj.status === 400 || !bufferObj.event) {
            console.log("后端返回报错")
            return
          }
          if (bufferObj.event === "message" || bufferObj.event === "agent_message") {
            // can not use format here. Because message is splited.
            unicodeToChar(bufferObj.answer)
            resultObj.conversationId = bufferObj.conversation_id
            resultObj.taskId = bufferObj.task_id
            resultObj.messageId = bufferObj.id
          } else if (bufferObj.event === "agent_thought") {
            console.log(bufferObj)
          } else if (bufferObj.event === "message_file") {
            console.log(bufferObj)
          } else if (bufferObj.event === "message_end") {
            setTimeout(() => {
              messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
              openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
            })
            isResponesEnd.value = true
          } else if (bufferObj.event === "message_replace") {
            console.log(bufferObj)
          } else if (bufferObj.event === "workflow_started") {
            console.log(bufferObj)
          } else if (bufferObj.event === "workflow_finished") {
            console.log(bufferObj)
          } else if (bufferObj.event === "node_started") {
            console.log(bufferObj)
          } else if (bufferObj.event === "node_finished") {
            console.log(bufferObj)
          } else if (bufferObj.event === "tts_message") {
            !show.value && audioPlayer.play(bufferObj.audio)
            messageObj.conversationId = bufferObj.conversation_id
            messageObj.taskId = bufferObj.task_id
            messageObj.messageId = bufferObj.id
          } else if (bufferObj.event === "tts_message_end") {
            tts_message_end.value = true
          }
        }
      })
      txt = lines[lines.length - 1]
    } catch (e) {
      console.log(e)
      return
    }
  }
}

const stop_tts = () => {
  if (!resultObj.taskId) {
    return
  }
  audioPlayer.pause()
  fetch(`https://smartai.chuangxing.ren/v1/chat-messages/${resultObj.taskId}/stop`, {
    method: "post",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer app-PXYjOI1hQvgSctOtOUPU9sey`
    },
    body: JSON.stringify({
      user: "abc-123"
    })
  })
}

const monitorList = [
  {
    id: 162,
    jk_name: "A库A12号后",
    tui_url: "192.168.1.122",
    longitude: "105.567288",
    latitude: "30.478192",
    xie_type: "HIKVISION",
    accoutName: "admin",
    password: "wrt123456",
    supervisory_type: 2,
    image_url: "http://wst-largescreen.chuangxing.ren",
    supervisory_name: "摄像头",
    supervisoryTypeTable: {
      id: 2,
      name: "摄像头",
      status: 1,
      create_time: 1730171266,
      update_time: 1730171266
    }
  }
  // {
  //   id: 163,
  //   jk_name: "A库全景2号",
  //   tui_url: "192.168.1.63",
  //   longitude: null,
  //   latitude: null,
  //   xie_type: "HIKVISION",
  //   accoutName: "admin",
  //   password: "wrt123456",
  //   supervisory_type: 2,
  //   image_url: "http://wst-largescreen.chuangxing.ren",
  //   supervisory_name: "摄像头",
  //   supervisoryTypeTable: {
  //     id: 2,
  //     name: "摄像头",
  //     status: 1,
  //     create_time: 1730171266,
  //     update_time: 1730171266
  //   }
  // },
  // {
  //   id: 166,
  //   jk_name: "A库A10.A11号前",
  //   tui_url: "192.168.1.147",
  //   longitude: "105.569095",
  //   latitude: "30.47575",
  //   xie_type: "HIKVISION",
  //   accoutName: "admin",
  //   password: "wrt123456",
  //   supervisory_type: 2,
  //   image_url: "http://wst-largescreen.chuangxing.ren",
  //   supervisory_name: "摄像头",
  //   supervisoryTypeTable: {
  //     id: 2,
  //     name: "摄像头",
  //     status: 1,
  //     create_time: 1730171266,
  //     update_time: 1730171266
  //   }
  // }
]

const src = computed(() => {
  try {
    const pn4 = monitorList[currentIndex.value].tui_url.split(".")
    const str = pn4[pn4.length - 1].padStart(3, "0")
    return str
  } catch (error) {
    return ""
  }
})

const currentIndex = ref(0)

const changeCurrentIndex = throttle((index) => {
  currentIndex.value = index
}, 500)

const handlerClick = (index) => {
  try {
    if (currentIndex.value === index) {
      return
    }
    changeCurrentIndex(index)
  } catch (error) {
    console.log(error)
  }
}

const addTask = (id) => {
  widgetStore.commit("addAttr", {
    name: "taskForm",
    meta: {
      props: {
        name: "dangerous1",
        id: props.id,
        use_id: id
      }
    }
  })

  widgetStore.dispatch("activate", "taskForm")
}

const task = throttle((data) => {
  realTime(data)
})

const realTime = (data) => {
  $message("正在查询设备信息。。。")
  axios
    .get(`http://183.63.206.104:8088/StandardApiAction_getDeviceOlStatus.action?jsession=${jsession.value}`, {
      params: {
        devIdno: data.device_no
      }
    })
    .then((res) => {
      console.log({
        ...data,
        eventId: props.id
      })
      if (res.data.onlines[0].online === 1) {
        stop_tts()
        store.commit("updateRealTime", {
          ...data,
          eventId: props.id
        })
      } else {
        $message("设备不在线")
      }
    })
    .catch(() => {
      $message("设备不在线")
    })
}

const data = ref({})

const get_appeal_detail = (id) => {
  $api.get("/api/index/get_appeal_detail", { id }).then((res) => {
    console.log(res)
    data.value = res.data
    console.log(data.value)
    $message(`事件已推送至  ${data.value.organization_name}`)
    messageData.value.push({
      role: "user",
      content: data.value?.title
      // content: dangerousData.value.handle_flow
    })
    getResult(data.value?.title)
    // getResult(
    //   `你是园区的管理助手，负责园区在发生响应事件时，与工作人员对话给出有助于工作人员快速响应的信息，请简要描述事件情况和处置建议。请注意，我们会讲你返回的内容转换为语音，所以你的回答必须要简短且完整的说出当前状态下的处置建议，并适当避免发散过多内容。当前情况：AI识别到了${dangerousData.value.event_place}，请迅速处理。`
    // )
  })
}

const simulation = () => {
  $message("功能待开发")
}

const showWuRenJi = inject("showWuRenJi")

const rescue = () => {
  // showWuRenJi()
  axios
    .get(`https://aiagent-api.sntyjt.com/prediction/dz/test?content=1&user_id=1339`, {
      headers: {
        authorization: "Bearer " + localStorage.getItem("token")
      }
    })
    .then((res) => {
      $message("无人机准备就绪~")
    })
}

const staff = ref([])

// const getStaff = () => {
//   axios.get("https://ydsq.chuangxing.ren/api/index/wanggeyuan_list").then((res) => {
//     staff.value = res.data.data.data
//   })
// }

const imgError = (e) => {
  e.target.src = "/img/defailtAvtar.png"
}

const frist = ref(true)

const jsession = ref(Cookies.get("jsession"))

const AIRefSwpier = ref()

const openRef = ref()

const voiceSwiper = ref()

const isImage = ref(false)

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia

const show = ref(false)

let audioContext
let bufferTime
let bufferData = []

function initAudio() {
  console.log("语音文字", audioContext)

  try {
    navigator?.getUserMedia(
      { audio: true },
      function (stream) {
        audioContext = new AudioContext()
        audioContext.resume()

        // 创建一个音频分析对象，采样的缓冲区大小为4096，输入和输出都是单声道
        const scriptProcessor = audioContext.createScriptProcessor(4096, 1, 1)
        // 开始处理音频
        scriptProcessor.onaudioprocess = function (e) {
          // 获得缓冲区的输入音频，转换为包含了PCM通道数据的32位浮点数组
          const buffer = e.inputBuffer.getChannelData(0)
          // 获取缓冲区中最大的音量值
          // eslint-disable-next-line prefer-spread
          const maxVal = Math.max.apply(Math, buffer)
          // 如果有声音的话，值为true,通过语音流去判断话筒是否有声音
          if (Math.round(maxVal * 100) > 0) {
            bufferData.push(...RecordingData(buffer))
            bufferTime && clearTimeout(bufferTime)
            bufferTime = setTimeout(function () {
              clearTimeout(bufferTime)
              bufferTime = null
              stopRecorder()
            }, 3000)
          } else {
            if (!bufferTime) {
              clearTimeout(bufferTime)
              bufferTime = null
              bufferTime = setTimeout(function () {
                clearTimeout(bufferTime)
                bufferTime = null
                stopRecorder()
              }, 3000)
            }
          }
        }

        // 将麦克风的声音输入这个对象
        const mediaStreamSource = audioContext.createMediaStreamSource(stream)
        // 将该分析对象与麦克风音频进行连接
        mediaStreamSource.connect(scriptProcessor)
        // 此举无甚效果，仅仅是因为解决 Chrome 自身的 bug
        scriptProcessor.connect(audioContext.destination)
        // 连接长连接
        connectWebSocket()
      },
      function (err) {
        console.log(err)
      }
    )
  } catch (error) {
    console.log(error)
  }
}

let webSocket
const APPID = "5ec244d5"
const API_SECRET = "37912e3e3f205e2a6201ec290452470a"
const API_KEY = "78b6c006f1f3df5e24d315e3dff09212"
const url = "wss://iat-api.xfyun.cn/v2/iat"
const host = "iat-api.xfyun.cn"

function getWebSocketUrl() {
  return new Promise((resolve, reject) => {
    // 请求地址根据语种不同变化
    const date = new Date().toGMTString()
    const algorithm = "hmac-sha256"
    const headers = "host date request-line"
    const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/iat HTTP/1.1`
    const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, API_SECRET)
    const signature = CryptoJS.enc.Base64.stringify(signatureSha)
    const authorizationOrigin = `api_key="${API_KEY}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
    const authorization = btoa(authorizationOrigin)
    resolve(`${url}?authorization=${authorization}&date=${date}&host=${host}`)
  })
}

// 连接websocket
function connectWebSocket() {
  return getWebSocketUrl().then((url) => {
    let iatWS
    if ("WebSocket" in window) {
      iatWS = new WebSocket(url)
    } else if ("MozWebSocket" in window) {
      // eslint-disable-next-line no-undef
      iatWS = new MozWebSocket(url)
    } else {
      alert("浏览器不支持WebSocket")
      return
    }
    webSocket = iatWS
    iatWS.onopen = (e) => {
      // 重新开始录音
      setTimeout(() => {
        webSocketSend()
      }, 500)
    }
    iatWS.onmessage = (e) => {
      result(e.data)
    }
    iatWS.onerror = (e) => {
      recorderStop()
    }
    iatWS.onclose = (e) => {
      recorderStop()
    }
  })
}

function toBase64(buffer) {
  let binary = ""
  const bytes = new Uint8Array(buffer)
  const len = bytes.byteLength
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i])
  }
  return window.btoa(binary)
}

// 向webSocket发送数据
function webSocketSend() {
  if (webSocket.readyState !== 1) {
    return
  }
  let audioData = bufferData.splice(0, 1280)
  const params = {
    common: {
      app_id: APPID
    },
    business: {
      language: "zh_cn", // 小语种可在控制台--语音听写（流式）--方言/语种处添加试用
      domain: "iat",
      accent: "mandarin" // 中文方言可在控制台--语音听写（流式）--方言/语种处添加试用
    },
    data: {
      status: 0,
      format: "audio/L16;rate=16000",
      encoding: "raw",
      audio: toBase64(audioData)
    }
  }

  webSocket.send(JSON.stringify(params))

  clearInterval(window.$handlerInterval)
  window.$handlerInterval = null
  window.$handlerInterval = setInterval(function () {
    // websocket未连接
    if (webSocket.readyState !== 1) {
      bufferData = []
      clearInterval(window.$handlerInterval)
      return
    }

    audioData = bufferData.splice(0, 1280)
    // 中间帧
    webSocket.send(
      JSON.stringify({
        data: {
          status: 1,
          format: "audio/L16;rate=16000",
          encoding: "raw",
          audio: toBase64(audioData)
        }
      })
    )
  }, 40)
}

function result(resultData) {
  // 识别结束
  const jsonData = JSON.parse(resultData)
  if (jsonData.data && jsonData.data.result) {
    const data = jsonData.data.result
    let str = ""
    const resultStr = ""
    const ws = data.ws
    for (let i = 0; i < ws.length; i++) {
      str = str + ws[i].cw[0].w
    }
    console.log("识别的结果为：", str)
    // 开启wpgs会有此字段(前提：在控制台开通动态修正功能)
    // 取值为 "apd"时表示该片结果是追加到前面的最终结果；取值为"rpl" 时表示替换前面的部分结果，替换范围为rg字段

    if (str && str !== "。" && str !== "?" && str !== "？" && str !== "！") {
      inputValue.value += str
      t_submit()
    }
  }
  if (jsonData.code === 0 && jsonData.data.status === 2) {
    webSocket.close()
  }
  if (jsonData.code !== 0) {
    webSocket.close()
    console.log(`${jsonData.code}:${jsonData.message}`)
  }
}

// 暂停录音
function recorderStop() {
  // safari下suspend后再次resume录音内容将是空白，设置safari下不做suspend
  if (!(/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgen))) {
    audioContext && audioContext.suspend()
  }
}

function addStart(e) {
  if (e.keyCode === 32 || e.keyCode === 12) {
    startRecorder()
  }
}

function startRecorder() {
  if (!show.value && isResponesEnd.value) {
    // show.value = true
    stop_tts()
    audioPlayer.pause()

    if (!audioContext) {
      initAudio()
    } else {
      audioContext.resume()
      connectWebSocket()
    }
  }
}

// 结束录音
function stopRecorder(val) {
  webSocket &&
    webSocket.send(
      JSON.stringify({
        data: {
          status: 2,
          format: "audio/L16;rate=16000",
          encoding: "raw",
          audio: ""
        }
      })
    )
  bufferData = []
  clearInterval(window.$handlerInterval)

  show.value = false
  audioContext?.suspend()
  document.body.removeEventListener("keydown", addStart)
}

// 确认事件
const fire_event_update = () => {
  axios.get(
    "https://wstsecure-api.chuangxing.ren/api/v1/fire_event_update?app_id=83ee227e01&identity=991d22cea8722095b32dff82dbfde6c2&event_id=" +
      dangerousData.value.id
  )
}

// 确认事件
const handelOk = () => {
  close()
}

onMounted(() => {
  // rescue()
  // get_appeal_detail()
  // getStaff()
  fire_event_update()
})

defineExpose({
  get_appeal_detail
})

onUnmounted(() => {
  stop_tts()
  show.value = false
  frist.value = false
})

watch([$realTime, show], [(newVal, oldVal) => {}], { deep: true })
</script>

<style lang="less" scoped>
.btnBox {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 0 10px;
  gap: 10px;

  .btn {
    background: linear-gradient(180deg, rgba(0, 36, 42, 0.5) 0%, rgba(0, 67, 78, 0.5) 100%);
    border: 1px solid #57ffff;
    width: 124;
    height: 29;
    gap: 10px;
    font-size: 10px;
    border-radius: 99px;
    border-width: 1px;
    padding: 5px 20px;
    cursor: pointer;
    color: #fff;
  }
}

.overlay,
.overlay1 {
  position: fixed;
  top: 0;
  width: 469px;
  height: 100px;
  background: #000;
  z-index: 1001;
  display: flex;
  flex-direction: column;
  font-size: 16px;
  font-weight: bold;
  color: #fff;

  .overlay-title {
    width: 100%;
    height: 45px;

    text-align: center;
    line-height: 45px;
  }

  .overlay-content {
    width: 100%;
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
  }
}

.overlay1 {
  width: 100%;
}

.dangerous {
  position: fixed;
  z-index: 1000;
  height: 585px;
  top: 160px;
  left: 50%;
  transform: translate(-50%);
  display: flex;

  &-left {
    background: rgba(0, 0, 0, 0.5);
    border-radius: 9px;
    display: flex;
    flex-direction: column;
    position: fixed;
    top: 0;
    height: 100%;
  }
}

#box1 {
  border: 1px solid #f34336;
  background: rgba(43, 5, 5, 0.5);
  backdrop-filter: blur(4px);
  padding: 4px 14px 11px;
  animation: animated-border 1s infinite;
  box-sizing: border-box;

  .left {
    width: 355px;
    height: 392px;
    overflow: hidden;
    line-height: 1.5;
  }

  .title {
    padding-bottom: 12px;
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;

    &::after {
      content: "";
      width: 100%;
      height: 2px;
      background: linear-gradient(90deg, rgba(243, 67, 54, 0) 0%, #f34336 91.76%);
      position: absolute;
      bottom: 0;
      left: 0;
    }

    img {
      width: 34px;
      height: 34px;
    }

    p {
      margin-left: 11px;
      font-size: 26px;
      font-weight: bold;
      color: #f34336;
      vertical-align: text-bottom;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .type {
      margin-left: 33px;

      p {
        font-size: 15px;
        font-weight: 500;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        &.name {
          padding-right: 4px;
        }

        &.value {
          color: #fff;
          margin-top: 0;
          margin-left: 2px;
          font-size: 13px;
        }
      }
    }

    .close {
      margin-left: auto;
      margin-right: 0;
      width: 26px;
      height: 26px;
    }
  }

  .name {
    color: #f34336;
    font-size: 15px;
    vertical-align: text-bottom;

    img {
      width: 27px;
      height: 21px;
      vertical-align: text-bottom;
    }
  }

  .value {
    color: #fff;
    font-weight: 500;
    margin-top: 4px;
    font-size: 13px;
  }

  #auto {
    height: 0;
    width: 0;
  }
}

.ai-swiper {
  width: 100%;
  overflow: hidden;
  height: 100%;

  .ai-content {
    background: #d7d7d75c;
    border-radius: 9px;
    padding: 8px;
    margin-top: 8px;
    gap: 11px;
    width: 100%;
    overflow: hidden;
    height: 350px;
    position: relative;

    > div {
      width: 100%;
      height: 100%;
      overflow: hidden auto;
      scrollbar-width: none;
      /* firefox */
      -ms-overflow-style: none;

      /* IE 10+ */
      &::-webkit-scrollbar {
        display: none;
        /* Chrome Safari */
      }

      div {
        max-width: 80%;
        line-height: 1.7;
        padding: 8px;
        border-radius: 9px;
        box-sizing: content-box;
        background: #fff;
        color: #252525;
        word-break: break-all;
        margin-top: 11px;
        font-size: 11px;
        // white-space: pre-line;

        &.use-message {
          margin-right: 0;
          margin-left: auto;
          background: #ffa9a9;
        }
      }
    }
  }

  .input-box {
    margin-top: 8px;
    height: 34px;
    border-radius: 34px;
    background: #fff;
    width: 100%;
    padding: 4px 4px 4px 11px;

    input {
      border: none;
      flex: 1 1 auto;
      height: 100%;
      margin-right: 9px;
      outline: none;
      font-size: 11px;
    }

    img {
      flex: 0 0 auto;
      height: 100%;
    }

    button {
      flex: 0 0 auto;
      height: 100%;
      border: 1px solid #f33636;
      background: #730000;
      color: #fff;
      padding: 4px 15px;
      border-radius: 34px;
      cursor: pointer;
      letter-spacing: 0.5px;
      font-size: 11px;
      margin-left: 4px;
    }
  }
}

.m-t-13 {
  margin-top: 12px;
}

.event-btn {
  margin-top: auto;
  width: 100%;
  margin-bottom: 0;
}

.right {
  width: 374px;
  height: 392px !important;
  overflow: hidden;
}

.m-t-12 {
  margin-top: 11px;
}

.m-t-14 {
  margin-top: 13px;
}

@keyframes animated-border {
  0% {
    box-shadow: 0 0 0 0 rgba(243, 67, 54, 0.8);
  }

  100% {
    box-shadow: 0 0 100px 100px rgba(243, 67, 54, 0);
  }
}

.user_info {
  padding: 11px 8px;
  height: 101px;

  img {
    width: 57px;
    height: 75px;
    border: 1px solid #f33636;
    margin-right: 13px;
    flex: 0 0 auto;
  }

  .user-box {
    height: 100%;
    line-height: 1.5;
    flex: 1 1 auto;
    color: #fff;
    font-weight: 500;

    .cF33636 {
      font-weight: 400;
    }

    p {
      font-size: 13px;
    }

    .btn-box {
      gap: 9px;

      button {
        padding: 4px 15px;
        border-radius: 6px;
        // background: #0611a9;
        // border: 1px solid #6dd3ff;
        border: 1px solid #f33636;
        background: #730000;
        color: #fff;
        font-size: 11px;
        letter-spacing: 0.5px;
        cursor: pointer;
      }
    }
  }
}

.m-t-24 {
  margin-top: 11px;
}

.monitor-swiper {
  margin-top: auto;
  margin-bottom: 0;

  .monitor-list {
    margin-top: 4px;
    height: 236px;
    overflow: hidden;

    ul {
      overflow: auto hidden;
      flex: 0 0 auto;
      margin-right: 7px;
      gap: 4px;
      scrollbar-width: none;
      /* firefox */
      -ms-overflow-style: none;

      /* IE 10+ */
      &::-webkit-scrollbar {
        display: none;
        /* Chrome Safari */
      }

      margin-bottom: 4px;

      li {
        border: 1px solid #f33636;
        width: 85px;
        height: 33px;
        box-sizing: border-box;
        cursor: pointer;
        background: #730000;
        margin-right: 4px;

        div {
          font-size: 11px;
          font-weight: bold;
        }

        img {
          width: 15px;
          height: 15px;
          margin-right: 4px;
        }
      }
    }

    .monitor-box {
      width: 355px;
      height: 200px;
      background: #000;
      border: 1px solid #f33636;
      margin-top: 4px;
    }
  }
}

.btn-content {
  gap: 9px;
  width: 100%;
  overflow: hidden;

  button {
    margin-top: 4px;
    border: 1px solid #f33636;
    background: #730000;
    color: #ffffff;
    border-radius: 6px;
    padding: 6px;
    cursor: pointer;
    white-space: nowrap;
    flex: 1 1 auto;
    font-size: 11px;
    width: 33.33%;
  }
}

.flex-0 {
  flex: 0 0 auto;
}

.flex {
  display: flex;
}

.flex-1 {
  flex: 1 1 auto;
}

.col {
  flex-direction: column;
}

.col-top {
  align-items: flex-start;
}

.h100 {
  height: 100%;
}

.w100 {
  width: 100%;
}

.w50 {
  width: 50%;
}

.cF33636 {
  color: #f33636;
}

.voice-swiper {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  border: 0.02rem solid #e0e7ff;
  background: rgba(0, 0, 0, 0.8);
  z-index: 991;
  text-align: center;
  display: flex;
  align-items: flex-end;

  .close {
    transition: all 0.5s;
    cursor: pointer;
    outline: none;
    padding: 23px;
    width: 19px;
    height: 19px;
    position: absolute;
    right: 14px;
    top: 9px;
    transform: rotate(-45deg);

    &::before {
      content: "";
      position: absolute;
      width: 50%;
      height: 2px;
      background: #fff;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }

    &::after {
      content: "";
      position: absolute;
      width: 2px;
      height: 50%;
      background: #fff;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .img-box {
    position: absolute;
    left: 50%;
    top: 50%;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -23px;
    margin-left: -23px;
    width: 94px;
    height: 94px;
    background: linear-gradient(115deg, #56d8e4 5%, #9f01ea 95%);
    border: 1px solid #e0e7ff;
    border-radius: 50%;

    &::before {
      content: "";
      position: absolute;
      display: inline-block;
      width: 47px;
      height: 47px;
      border: 1px solid #9f01ea;
      box-shadow: 0px 0px 3px 0px #9f01ea;
      border-radius: 50%;
      animation: move 1.5s infinite;
    }

    &::after {
      content: "";
      position: absolute;
      display: inline-block;
      width: 47px;
      height: 47px;
      border: 1px solid #56d8e4;
      box-shadow: 0px 0px 3px 0px #56d8e4;
      border-radius: 50%;
      animation: move 1.5s 0.5s infinite;
    }

    img {
      width: 28px;
      height: 47px;
    }
  }

  @keyframes move {
    0% {
      opacity: 1;
      transform: scale(1);
    }

    100% {
      opacity: 0;
      transform: scale(2);
    }
  }
}

.rela {
  position: relative;
}

.line-1 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

.staff-swiper {
  position: absolute;
  top: -6px;
  left: -9px;
  width: 100%;
  padding: 9px;
  box-sizing: content-box;
  background: #2b0505cc;
  backdrop-filter: blur(4px);
  height: 389px;
  z-index: 999;

  .close {
    border: 1px solid #f33636;
    background: #730000;
    border-radius: 6px;
    padding: 4px 15px;
    color: #fff;
    cursor: pointer;

    img {
      width: 19px;
      height: 19px;
      margin-right: 9px;
    }
  }

  .content {
    margin-top: 4px;
    flex-wrap: wrap;
    height: 353px;
    overflow: hidden auto;
    scrollbar-width: none;
    /* firefox */
    -ms-overflow-style: none;

    /* IE 10+ */
    &::-webkit-scrollbar {
      display: none;
      /* Chrome Safari */
    }

    .item {
      background: #fff;
    }
  }
}

.v-enter-active,
.v-leave-active {
  transition: all 0.5s ease;
  overflow: hidden;
}

.v-enter-from,
.v-leave-to {
  top: 100%;
  height: 0 !important;
}

.content-enter-active,
.content-leave-active {
  transition: all 0.5s ease;
}

.content-enter-from,
.content-leave-to {
  width: 0px !important;
}

.popup-ai {
  position: fixed;
  left: 100%;
  top: 0;
  padding: 11px;
  background: rgba(0, 0, 0, 0.5);
  // height: 86vh;
  height: 100%;
  width: 243px;
  color: #000;

  > div {
    width: 100%;
    height: 100%;
    overflow: hidden auto;
    scrollbar-width: none;
    /* firefox */
    -ms-overflow-style: none;

    /* IE 10+ */
    &::-webkit-scrollbar {
      display: none;
      /* Chrome Safari */
    }

    div {
      max-width: 80%;
      line-height: 1.7;
      padding: 4px;
      border-radius: 5px;
      box-sizing: content-box;
      background: #fff;
      color: #252525;
      word-break: break-all;
      margin-top: 13px;
      font-size: 9px;
      // white-space: pre-line;

      &.use-message {
        margin-right: 0;
        margin-left: auto;
        background: #ffa9a9;
      }
    }
  }
}
</style>
